package com.yzh.croom.service;

import com.yzh.croom.model.domain.Role;
import com.yzh.croom.model.domain.User;
import com.yzh.croom.repository.RoleRepository;
import com.yzh.croom.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private RoleRepository roleRepository;

    //根据账号查询用户
    public User getUser(String account){
        User user = null;
        Object obj = redisTemplate.opsForValue().get("user_" + account);
        if (obj != null){
            user = (User)obj;
        } else {
            user = userRepository.findByAccount(account);
            if (user != null){
                redisTemplate.opsForValue().set("user_" + account, user,10, TimeUnit.SECONDS);
            }
        }
        return user;
    }

    //根据账号查询用户权限
    public List<Role> getUserAuthorities(String account){
        List<Role> authorities = null;
        Object obj = redisTemplate.opsForValue().get("authorities_" + account);
        if (obj != null){
            authorities = (List<Role>) obj;
        } else {
            List<Role> authoritiesByAccount = roleRepository.findAuthoritesByAccount(account);
            if (authoritiesByAccount != null){
                redisTemplate.opsForValue().set("authorities_" + account, authoritiesByAccount,10,TimeUnit.SECONDS);
            }
        }
        return authorities;
    }
}
